import xlsx from 'xlsx'
import type { WorkBook } from 'xlsx'
import type { JsonToSheet, AoAToSheet } from './typing'

const { utils, writeFile } = xlsx

const DEF_FILE_NAME = 'excel-list.xlsx'

export function jsonToSheetXlsx<T = any>({
  data,
  header,
  filename = DEF_FILE_NAME,
  json2sheetOpts = {},
  write2excelOpts = { bookType: 'xlsx' },
}: JsonToSheet<T>) {
  const arrData = [...data]
  if (header) {
    arrData.unshift(header)
    json2sheetOpts.skipHeader = true
  }

  const worksheet = utils.json_to_sheet(arrData, json2sheetOpts)

  /* 将工作表添加到工作簿 */
  const workbook: WorkBook = {
    SheetNames: [filename],
    Sheets: {
      [filename]: worksheet,
    },
  }
  /* 由文件名决定的输出格式*/
  writeFile(workbook, filename, write2excelOpts)
  /*此时，out.xlsb 将已下载 */
}

export function aoaToSheetXlsx<T = any>({
  data,
  header,
  filename = DEF_FILE_NAME,
  write2excelOpts = { bookType: 'xlsx' },
}: AoAToSheet<T>) {
  const arrData = [...data]
  if (header) {
    arrData.unshift(header)
  }

  const worksheet = utils.aoa_to_sheet(arrData)

  /* 将工作表添加到工作簿 */
  const workbook: WorkBook = {
    SheetNames: [filename],
    Sheets: {
      [filename]: worksheet,
    },
  }
  /* 由文件名决定的输出格式 */
  writeFile(workbook, filename, write2excelOpts)
  /* 此时，out.xlsb 将已下载 */
}
